/**
 * @author mmbro
 * @homepage https://gitee.com/mmbro/
 * @date 2021年05月18日10:56:48
 * @description 注释: 图片资源工具类
 */
class ImageSourceUtil{

    /**
     * 获取网址Base64数据
     * (自动添加跨域)
     * @param url 下载网址
     * @returns {Promise<string>} base64数据
     */
    getURLBase64(url) {
        return new Promise((resolve, reject) => {
            let xhr = new XMLHttpRequest();
            xhr.open('get', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (this.status === 200) {
                    let blob = this.response;
                    let fileReader = new FileReader();
                    fileReader.onloadend = function (e) {
                        let result = e.target['result'];
                        resolve(result)
                    };
                    fileReader.readAsDataURL(blob)
                }
            };
            xhr.onerror = function () {
                reject()
            };
            xhr.send()
        })
    }

    /**
     * 获取网址Base64数据
     * (自动添加跨域)
     * @param url 下载网址
     * @returns {Promise<string>} base64数据
     */
    getURLText(url) {
        return new Promise((resolve, reject) => {
            let xhr = new XMLHttpRequest();
            xhr.open('get', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (this.status === 200) {
                    let blob = this.response;
                    let fileReader = new FileReader();
                    fileReader.onloadend = function (e) {
                        let result = e.target['result'];
                        resolve(result)
                    };
                    fileReader.readAsText(blob)
                }
            };
            xhr.onerror = function () {
                reject()
            };
            xhr.send()
        });
    }

    /**
     * 通过canvas获取img图片元素的图片base64
     * @param img
     * @returns {string}
     */
    getBase64Image(img) {
        let dataURL;
        let canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        let ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        dataURL = canvas.toDataURL("image/png");
        return dataURL;
        //return dataURL.replace("data:image/png;base64,", "");
    }

    /**
     * 创建Element元素
     * @param label
     * @returns {*}
     */
    createElement(label) {
        let ele;
        ele = document.createElement(label);
        if (label === 'img') {
            // 设置图片跨域访问
            ele.crossOrigin = 'Anonymous';
        }
        return ele;
    }

    /**
     * 测试工具类中的方法
     * @param picUrl 测试用图片url(需要支持cors跨域)
     */
    test(picUrl = '//e.7mo.org:18000/url?url=https://www.baidu.com/img/flexible/logo/pc/result.png') {

        let testPic = "http://127.0.0.1:18000/image/2665.png";
        testPic = "./image/2665.png";

        if (!!picUrl) {
            testPic = picUrl;
        } else {
            let ipPromise = this.getURLText(location.origin + '/ip');
            ipPromise.then(ip => {
                if (!!ip) {
                    testPic = testPic.replace('127.0.0.1', ip);
                }
            });
        }

        let _this = this;

        async function testCrossDomain(url) {
            let data = await _this.getURLBase64(url);
            let re = document.getElementById('result');
            if (!re) {
                let div = _this.createElement('div');
                document.body.appendChild(div);
                re = div;
            }
            if (data.length > 0) {
                re.innerHTML = data + '<br/>' + data.length;
                let imgEle = _this.createElement('img');
                imgEle.src = data;
                re.appendChild(_this.createElement('br'))
                re.appendChild(imgEle);
            } else {
                re.innerText = 'failed!';
            }
        }

        function testCrossDomain1(url) {
            let img = _this.createElement('img');
            let re = document.getElementById('result');
            if (!re) {
                let div = _this.createElement('div');
                document.body.appendChild(div);
                re = div;
            }
            img.onload = (evt) => {
                let width = evt.target.width;
                console.log('onload', evt, width);
                if (width !== 0) {
                    re.innerText = 'getting base64!';
                    let data = _this.getBase64Image(img);
                    if (data.length > 0) {
                        re.innerHTML = data + '<br/>' + data.length;
                        let imgEle = _this.createElement('img');
                        imgEle.src = data;
                        re.appendChild(_this.createElement('br'))
                        re.appendChild(imgEle);
                    } else {
                        re.innerText = 'base64 failed!';
                    }
                } else {
                    re.innerText = 'get img failed!';
                }
            };
            img.src = url;
        }

        testCrossDomain(testPic).then(r => console.log('testCrossDomain finished', r));
        testCrossDomain1(testPic);
    }
}